package com.itwn.realm;

import com.itwn.bean.User;
import com.itwn.service.UserService;
import jdk.nashorn.internal.parser.Token;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * @Description:
 * @ClassName: MyRealm
 * @Author: 流光亦断
 * @Date: 2021/8/20 12:14
 * @Version: 1.0     // 版本
 */
public class MyRealm extends AuthorizingRealm {
@Autowired
private UserService userService;
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        String userNo = (String) principals.getPrimaryPrincipal();
        //根据账户查询处对应的角色
        List<String> list = userService.getRoles(userNo);
        Set<String> roles=new HashSet<>(list);
        SimpleAuthorizationInfo info=new SimpleAuthorizationInfo(roles);
        return info;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        UsernamePasswordToken userToken=(UsernamePasswordToken) token;
        User user = userService.userLogin(userToken.getUsername());
        if(user==null){
            throw new UnknownAccountException("用户名认证失败。。。");
        }
        Object principal = user.getUserNo();//从数据库查询出来的账户
        Object hashedCredentials = user.getCodePass();//从数据库中查询到密码
        ByteSource credentialsSalt = ByteSource.Util.bytes(user.getSaltValue());//从数据库中查询出来的盐值
        String realmName=getName();//认证对象的名字
        SimpleAuthenticationInfo info=new SimpleAuthenticationInfo(principal,hashedCredentials,credentialsSalt,realmName);
        System.out.println(info.toString());
        return info;
    }
}
